package com.example.pceb.controller;

import com.example.pceb.entity.Achievement;
import com.example.pceb.result.Result;
import com.example.pceb.service.AchievementService;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.List;
import java.util.Map;

@RestController
//@CrossOrigin(origins = "*")
@RequestMapping("/api/achievements")
public class AchievementController {

    @Autowired
    private AchievementService achievementService;

    // 获取当前用户的所有成果
    @GetMapping("/{username}")
    public Result<?> getByUsername(@PathVariable String username) {
        List<Achievement> list = achievementService.getByUsername(username);
        return Result.success(list);
    }

    // 新增或修改成果
    @PostMapping("/save")
    public Result<?> save(@RequestBody Achievement achievement) {
        achievementService.saveOrUpdate(achievement);
        return Result.success();
    }

    // 删除成果
    @DeleteMapping("/delete/{id}")
    public Result<?> delete(@PathVariable Long id) {
        achievementService.removeById(id);
        return Result.success();
    }

    //返回获奖网页的pdf  6.29
    @PostMapping("/pdf")
    public void generatePdf(@RequestBody Map<String, String> map, HttpServletResponse response) throws Exception {
        String url = map.get("url");

        // PDF 临时文件
        File pdfFile = File.createTempFile("achievement-", ".pdf");

        // 调用 wkhtmltopdf 命令（需预先安装），我下载在D盘路径下面，运行时候先下载，换成自己的下载路径就可以用了
        ProcessBuilder pb = new ProcessBuilder("\"D:\\wkhtmltopdf\\bin\\wkhtmltopdf.exe\"", url, pdfFile.getAbsolutePath());
        Process process = pb.start();
        process.waitFor();

        // 设置响应头，返回 PDF
        response.setContentType("application/pdf");
        response.setHeader("Content-Disposition", "attachment; filename=achievement.pdf");

        try (InputStream in = new FileInputStream(pdfFile);
             OutputStream out = response.getOutputStream()) {
            byte[] buf = new byte[1024];
            int len;
            while ((len = in.read(buf)) > 0) {
                out.write(buf, 0, len);
            }
        }

        pdfFile.delete(); // 删除临时文件
    }
    /**
     * 搜索学生成果
     * @param keyword 关键词（username或title）
     * @return 匹配的成果列表
     */
    //搜索学生成果 6.30
    @GetMapping("/search")
    public Result<List<Achievement>> searchAchievements(@RequestParam(required = false) String keyword) {
        List<Achievement> list = achievementService.searchAchievements(keyword);
        return Result.success(list);
    }

        // 模糊提示 6.30
        @GetMapping("/suggestions")
        public Result<List<String>> getSuggestions(@RequestParam String keyword) {
            List<String> suggestions = achievementService.getSuggestions(keyword);
            return Result.success(suggestions);
        }


}

